# -*- coding: utf-8 -*-
# @File : .py
# @Author : ZhouHang
# @Date : 20-4-8
# @Desc :

# url(r'^users/$', views.UserView.as_view()),
import re

from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.generics import CreateAPIView
from rest_framework_jwt.settings import api_settings
from celery_tasks.send_email import tasks


from users.models import User, Address
from django.core.mail import send_mail


class CreateUserSerializer(serializers.ModelSerializer):
    """
    创建用户序列化器
    """
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登陆状态token', read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """
        创建用户
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # user = super().create(validated_data)
        user = User.objects.create(**validated_data)
        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save() #
        # 设置jwt 上面的save是创建对象　将数据保存到数据库　jwt设置属性不属于数据库中内容　故需要放到其下面
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token


        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active_status')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email']

    def update(self, instance, validated_data):
        email = validated_data["email"]
        instance.email = email
        instance.save()
        verify_url = instance.generate_verify_email_url()

        tasks.send_email.delay(email, verify_url)

        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        validated_data["user"] = self.context["request"].user
        instance = super().create(validated_data)
        return instance


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class UserPwdUpdate(serializers.ModelSerializer):
    # id = serializers.CharField(label="用户编号", read_only=True)
    new_pwd = serializers.CharField(label="新密码", write_only=True)
    repeat_pwd = serializers.CharField(label="确认密码", write_only=True)
    class Meta:
        model = User
        fields = ["id","password", "new_pwd","repeat_pwd"]

        extra_kwargs = {
            'id': {
                'read_only': True,


            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
            'new_pwd': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
            'repeat_pwd': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, data):
        password = data.get("password")
        # print(password)
        new_pwd = data.get("new_pwd")
        repeat_pwd = data.get("repeat_pwd")


        user = self.context["request"].user
        # print(user.set_password("wwwwwwww"))

        if not user.check_password(password):
            return ValueError({"meassage":"密码校验失败"})

        return data

    def update(self, instance, validated_data):
        # print("dsa"*80)
        new_pwd = validated_data.get("new_pwd")
        # user = self.context["request"].user
        instance.set_password(new_pwd)
        instance.save()
        return instance

